<template>
  <div class="default-main ba-table-box">
    <div class="block">
      <div class="table-block">
        <el-alert class="ba-table-alert"
                  v-if="baTable.table.remark"
                  :title="baTable.table.remark"
                  type="info"
                  show-icon />
        <el-collapse v-model="activeNames"
                     class="cp">
          <el-collapse-item name="1">
            <template #title>
              <span>计算公式</span>
              <span class="tip">展开可查看公式</span>
            </template>
            <el-row type="flex"
                    align="middle">
              <template v-for="(dom, i) in doms1"
                        :key="i">
                <el-tooltip effect="light"
                            placement="top"
                            popper-class="doms">
                  <template #content>
                    <span class="labels">{{ dom.content }}</span>
                  </template>
                  <el-button>{{ dom.label }}</el-button>
                </el-tooltip>
                <span class="fuhao"
                      v-if="i != doms1.length - 1">{{ i == 0 ? '=' : i == 1 ? '*' : '-'}}</span>
              </template>
            </el-row>
            <el-row type="flex"
                    align="middle">
              <template v-for="(dom, i) in doms2"
                        :key="i">
                <el-tooltip effect="light"
                            placement="top"
                            popper-class="doms">
                  <template #content>
                    <span class="labels">{{ dom.content }}</span>
                  </template>
                  <el-button>{{ dom.label }}</el-button>
                </el-tooltip>
                <span class="fuhao"
                      v-if="i != doms2.length - 1">{{ i == 0 ? '=' : '+' }}</span>
              </template>
            </el-row>
          </el-collapse-item>
        </el-collapse>
        <!-- 表格顶部菜单 -->
        <TableHeader :buttons="['refresh', 'add', 'edit', 'delete', 'comSearch', 'quickSearch', 'columnDisplay']"
                     :quick-search-placeholder="t('Quick search placeholder', { fields: '订单号' })">
          <template #campaign>
            <el-autocomplete v-model="baTable.comSearch.form['campaign']"
                             :fetch-suggestions="querySearch"
                             :trigger-on-focus="false"
                             clearable
                             placeholder="搜索名称/ID"
                             value-key="label"
                             @select="handleSelect"
                             @change="handleChange" />
          </template>
          <template #time>
            <el-date-picker v-model="baTable.comSearch.form['time']"
                            type="daterange"
                            range-separator="至"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间"
                            :shortcuts="shortcuts"
                            value-format="YYYY-MM-DD" />
          </template>
        </TableHeader>

        <el-row style="margin: 10px 0;"
                :gutter="10">
          <el-col :span="1.5">
            <el-button type="warning"
                       @click="exportExcelOperate"
                       :loading="state.buttonLoading"
                       v-if="baTable.auth('export')">
              <Icon :color="'#ffffff'"
                    name="el-icon-Position" />导出
            </el-button>
          </el-col>
          <!-- <el-col :span="1.5" class="tipText">
            <span>默认显示昨天的数据</span>
          </el-col> -->
        </el-row>

        <Table show-summary
               :summary-method="getSummaries"></Table>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, provide, markRaw } from 'vue'
import baTableClass from '/@/utils/baTable'
// import PopupForm from './popupForm.vue'
import NameCol from './nameCol.vue'
import Table from '/@/components/table/index.vue'
import TableHeader from '/@/components/table/header/index.vue'
import { baTableApi, fileDownload } from '/@/api/common'
import Cookies from 'js-cookie'
import { useI18n } from 'vue-i18n'
import { ElMessageBox } from 'element-plus'
import { exportExcel } from '/@/api/backend/advertisement/performanceReport'

defineOptions({
    name: 'advertisement/performanceReport',
})
const { t } = useI18n()
const state: {
    buttonLoading: boolean
} = reactive({
    buttonLoading: false
})
const activeNames = ref('')
const doms1 = [
    {
        label: '盈利',
        content: '盈利'
    },
    {
        label: '收入',
        content: '收入'
    },
    {
        label: '(1-退款率-手续费率)',
        content: '(1-退款率-手续费率)'
    },
    {
        label: '花费',
        content: '花费'
    },
    {
        label: '采购成本/7.106',
        content: '件数(订单量*1.5) * 22.98'
    },
    {
        label: '头程/7.106',
        content: '件数(订单量*1.5) * 14.48'
    },
    {
        label: '海外仓成本合计',
        content: '海外仓成本合计'
    }
]
const doms2 = [
    {
        label: '海外仓成本合计',
        content: '海外仓成本合计'
    },
    {
        label: '入库费',
        content: '0.082*件数(订单量*1.5)'
    },
    {
        label: '订单处理费',
        content: '0.5*订单量'
    },
    {
        label: '分拣费',
        content: '0.5*实时订单量'
    },
    {
        label: '包装费',
        content: '0.15*订单量/2'
    },
    {
        label: '海外仓配送费',
        content: '6.28*订单量'
    }
]
const shortcuts = [
    {
        text: '昨天',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 1)
            end.setTime(end.getTime() - 3600 * 1000 * 24 * 1)
            return [start, end]
        }
    },
    {
        text: '过去7天',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            end.setTime(end.getTime() - 3600 * 1000 * 24 * 1)
            return [start, end]
        }
    },
    {
        text: '过去30天',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            end.setTime(end.getTime() - 3600 * 1000 * 24 * 1)
            return [start, end]
        }
    }
]
const inputText = ref()
const querySearch = (queryString: string, cb: any) => {
  cb([
    {
        value: 1,
        label: '推广系列名称/ID'
    },
    {
        value: 2,
        label: '广告名/ID'
    },
  ])
}

const baTable = new baTableClass(
    new baTableApi('/advertisement/performanceReport/'),
    {
        column: [
            {
                label: '姓名', 
                prop: 'name', 
                render: 'customRender', 
                align: 'center',
                customRender: markRaw(NameCol) , 
                operator: false
            },
            {
                label: '团队归属地',
                prop: 'company',
                align: 'center',
                comSearchRender: 'select',
                replaceValue: {
                    '武汉': '武汉',
                    '银川': '银川'
                }
            },
            {   
                label: '花费', 
                prop: 'spend', 
                align: 'center',
                operator: false,
                sortable: 'custom'
            },
            {   
                label: '收入', 
                prop: 'total_onsite_shopping_value', 
                align: 'center',
                operator: false,
                sortable: 'custom'
            },
            {   
                label: '订单', 
                prop: 'conversion', 
                align: 'center',
                operator: false,
                sortable: 'custom'
            },
            {   
                label: 'ROI', 
                prop: 'onsite_shopping_roas', 
                align: 'center',
                operator: false,
                sortable: 'custom'
            },
            {   
                label: '盈利', 
                prop: 'profit', 
                align: 'center',
                operator: false,
                sortable: 'custom'
            },
            {   
                label: '实时转化', 
                prop: 'real_time_conversion', 
                align: 'center',
                operator: false,
                sortable: 'custom'
            },
            {   
                label: '实时收入', 
                prop: 'RealTimeRevenue', 
                align: 'center',
                operator: false,
                sortable: 'custom'
            },
            {   
                label: '实时ROI', 
                prop: 'RealTimeRoi', 
                align: 'center',
                operator: false,
                sortable: 'custom'
            },
            {   
                label: '实时盈利', 
                prop: 'profit_new', 
                align: 'center',
                operator: false,
                sortable: 'custom'
            },
            { 
                label: '时间', 
                prop: 'stat_time_day', 
                align: 'center', 
                render: 'datetime', 
                sortable: 'custom', 
                operator: 'RANGE', 
                width: 160 
            }
        ],
        dblClickNotEditColumn: ['all']
    },
    {
        defaultItems: {
            status: '1',
        }
    }
)

provide('baTable', baTable)

baTable.mount()
baTable.getIndex()

const getSummaries = (param:any) => {
  const { columns, data } = param
  const sums: string[] = []
  columns.forEach((column:any, index:any) => {
    const key = column.columnKey
    switch(key){
        case 'name':
            sums[index] = `总计: ${String(baTable.table.total)}条`
            break
        case 'spend':
            sums[index] = `${baTable.table.extend?.spend} USD`
            break
        case 'total_onsite_shopping_value':
            sums[index] = `${baTable.table.extend?.total_onsite_shopping_value} USD`
            break
        case 'conversion':
            sums[index] = `${baTable.table.extend?.conversion}`
            break
        case 'onsite_shopping_roas':
            sums[index] = `${baTable.table.extend?.onsite_shopping_roas}`
            break
        case 'profit':
            sums[index] = `${baTable.table.extend?.profits} USD`
            break
        case 'real_time_conversion':
            sums[index] = `${baTable.table.extend?.real_time_conversion} USD`
            break
        case 'RealTimeRoi':
            sums[index] = baTable.table.extend?.roi_new
            break
        case 'profit_new':
            sums[index] = `${baTable.table.extend?.profits_new} USD`
            break
        case 'RealTimeRevenue':
            sums[index] = `${baTable.table.extend?.RealTimeRevenue_new} USD`
            break
        default:
            sums[index] = ''
    }
  })
  return sums
}

const exportExcelOperate = () => {
    state.buttonLoading = true
    baTable.table.loading = true
    ElMessageBox.confirm(
        '是否确认导出所有数据项?',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        type keymaps = {
            [key: string]: string | number
        }
        const obj:keymaps = {}
        baTable.table.filter?.search!.forEach(v => {
            obj[v.field] = v.val
        }) || []
        exportExcel('post', obj).then(response => {
            fileDownload(response, Cookies.get('filename') || 'file.xlsx')
        }).catch(err => {
            state.buttonLoading = false
            baTable.table.loading = false
        }).finally(() => { 
            state.buttonLoading = false
            baTable.table.loading = false
        })
        state.buttonLoading = false
        baTable.table.loading = false
    }).catch(() => {
        state.buttonLoading = false
        baTable.table.loading = false
    })
}

const handleSelect = (item: Record<string, any>) => {
    baTable.comSearch.form['campaign'] = inputText.value
    const comSearchData: Array<any> = baTable.table.filter?.search || []
    comSearchData.push({
        field: 'campaign',
        val: inputText.value,
        operator: '',
        render: ''
    })
    comSearchData.push({
        field: 'type',
        val: item.value,
        operator: '',
        render: ''
    })
    baTable.onTableAction('com-search', comSearchData)
}

const handleChange = (value: string | number) => {
    inputText.value = value
}

</script>

<style scoped lang="scss">
:deep(.el-date-editor.el-input__wrapper){
    width: initial;
}
.tipText{
    display: flex;
    align-items: center;
    font-size: 16px;
    color: #F56C6C;
}
.cp{
    .el-row{
        margin: 15px 0;
    }
    :deep(.el-collapse-item__header){
        position: relative;
        padding: 0 10px;
        font-size: 16px;
    }
    .tip{
        position: absolute;
        right: 6%;
        color: #888;
        font-size: 12px;
    }
    :deep(.el-collapse-item__content){
        padding: 0 10px 25px;
    }
    .fuhao{
        font-size: 16px;
        padding: 0 5px;
    }
    .ml-label{
        font-weight: bold;
        font-size: 16px;
        color: #f00;
    }
    .ml-input{
        width: 200px;
    }
}
</style>
